<template>
  <base-modal
    size="mini"
    :title="$t('task.taskTypes.planTask.changeTime')"
    :show.sync="visible"
    width="500px"
    class="change-time-dialog"
  >
    <div class="base-modal-content change-time-dialog-content">
      <el-form
        ref="form"
        class="form-container"
        :rules="rules"
        label-position="top"
        :model="form"
      >
        <el-form-item :label="$t('task.taskTypes.planTask.estimatedCreationTime')" prop="planTime">
          <el-date-picker
            id="form_smart_plan_create_time"
            type="datetime"
            :prefix-icon="`iconfont icon-fdn-datetime`"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd HH:mm"
            value-format="timestamp"
            :placeholder="$t('common.placeholder.select')"
            v-model="form.planTime" 
            :clearable="clearable" 
            :default-time="defaultTime"
            popper-class="change-time-picker"
          />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit" :disabled="pending">{{$t('common.base.makeSure')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* api */
import { planAdjustTime } from '@src/modules/smartPlan/api/index.js'
/* util */
import { getPlanStartTime } from 'pub-bbx-utils'
import { safeNewDate } from '@src/util/time';
import { t } from '@src/locales';
import _ from 'lodash'
let maxDate;

export default {
  name: 'change-time-dialog',
  props: {
    dateType: {
      type: String,
      default: 'datetime'
    },
    clearable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      visible: false,
      pending: false,
      form: {
        planTime: '',
      },
      pickerOptions: {
        disabledDate(time) {
          let minDate = safeNewDate().getTime() - 8.64e7
          if (maxDate) return time.getTime() < minDate || time.getTime() > maxDate
          return time.getTime() < minDate
        }
      },
      planId: '',
      jobId: '',
      rules: {
        planTime: [
          { required: true, message: t('common.placeholder.select'), trigger: 'change' },
          { validator: this.checkPlanTime, trigger: ['blur', 'change'] },
        ]
      }
    }
  },
  computed: {
    defaultTime() {
      return getPlanStartTime(safeNewDate(), 'task').split(' ')[1]
    },
  },
  methods: {
    /**
    * @description 打开计划时间弹窗
    */
    openDialog(row) {
      this.visible = true
      maxDate = row.maxDate
      this.planId = row.planId
      this.jobId = row.planJobDetail?.id
      this.form.planTime = row.planJobDetail?.planTime || ''
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    checkPlanTime: _.debounce(function(rule, value, callback) {
      if (!value) return callback()
      if (this.dateType == 'datetime') {
        let nowTime = safeNewDate().getTime();
        if (value < nowTime) callback(new Error(t('task.tip.planTimeTip3', {data: ''})))
        if (maxDate && value > maxDate) callback(new Error(t('smartPlan.tips.tip7')))
      }
      callback()
    }, 1000),
    submit() {
      this.$refs.form.validate().then(valid => {
        if (valid) {
          let planTime = this.form.planTime;
          let params = { 
            id: this.planId,
            jobId: this.jobId,
            planTime
          }
          
          if (this.pending) return;
          this.pending = true;
          
          planAdjustTime(params)
            .then(res => {
              if (res.succ) {
                this.$platform.notification({
                  title: t('common.base.tip.editSuccess'),
                  type: 'success'
                })
                this.visible = false
                this.$emit('planAdjustTimeSuccess')
              } else {
                this.$platform.notification({
                  title: res.message,
                  type: 'error'
                });
              }
            })
            .finally(() => {
              this.pending = false
            })
        }
      })
      
    }
  }
}
</script>

<style lang="scss">
.change-time-dialog {
  .form-container {
    padding: 24px;
  }
}
.change-time-picker .el-picker-panel__footer button:first-child {
  display: none;
}
</style>
